const http = require('../../../utils/https.js');

Page({
    data: {
        flashSaleInfo: {}, // 商品 + 活动整体信息
        productImages: [], // 轮播图
        productDetail: '', // 富文本
        time: 0, // 倒计时总毫秒数
        timeData: {
            hours: 0,
            minutes: 0,
            seconds: 0
        },
        appraiseNum: 0,
        appraise: [],
        cartCount: 0
    },

    onLoad(options) {
        console.log('商品id', options.productId);
        this.productId = options.productId;

        // 先获取商品详情
        this.getFlashSaleDetail(options.productId, () => {
            // 再获取活动信息
            this.getActivityInfo(options.productId);
        });

        // 获取评论
        this.getComments(options.productId);
    },

  /**
   * 获取商品详情
   */
  getFlashSaleDetail(productId, callback) {
      wx.showLoading({
          title: '加载中...'
      });
      http.GET(
          '/product/productinfo/list', {
              id: productId
          },
          (res) => {
              wx.hideLoading();
              if (res.code === 200 && res.rows && res.rows.length > 0) {
                  const data = res.rows[0];

                  // 轮播图
                  let images = [];
                  if (data.productImages && data.productImages.length > 0) {
                      data.productImages.forEach(imgObj => {
                          if (imgObj.url) {
                              images = images.concat(imgObj.url.split(',').map(u => u.trim()));
                          }
                      });
                  } else {
                      images = [data.mainImage, data.image].filter(Boolean);
                  }

                  // 富文本详情
                  let detail = data.productDetail?.description || '<p>暂无详细介绍</p>';

                  // ✅ 给 img 标签加自适应样式，防止超出屏幕
                  detail = detail.replace(
                      /<img/gi,
                      '<img style="max-width:100%;height:auto;display:block;"'
                  );

                  this.setData({
                      flashSaleInfo: data,
                      productImages: images,
                      productDetail: detail
                  });

                  if (typeof callback === 'function') {
                      callback();
                  }
              } else {
                  wx.showToast({
                      title: '获取商品信息失败',
                      icon: 'none'
                  });
              }
          },
          (err) => {
              wx.hideLoading();
              wx.showToast({
                  title: '网络请求失败',
                  icon: 'none'
              });
              console.error('获取商品详情失败:', err);
          }
      );
  },


    /**
     * 获取活动信息（倒计时 + 活动价 + 库存）
     */
    getActivityInfo(productId) {
        http.GET('/activity/promotion/list', {
            productId
        }, (res) => {
            if (res.code === 200 && res.rows && res.rows.length > 0) {
                const act = res.rows[0];
                const activityType = act.activityType || {};
                const product = act.product || {};

                // 活动价改为 value
                const flashPrice = product.price * act.value;
                const stock = product.stock;

                const endTimeStr = activityType.endTime;
                if (!flashPrice || !stock || !endTimeStr) {
                    console.error('活动数据不完整', act);
                    wx.showToast({
                        title: '活动信息不完整',
                        icon: 'none'
                    });
                    return;
                }

                // 时间格式处理
                let formattedEndTime = endTimeStr;
                if (formattedEndTime.length === 16) formattedEndTime += ':00';
                formattedEndTime = formattedEndTime.replace(/-/g, '/');
                const endTime = new Date(formattedEndTime).getTime();

                if (isNaN(endTime)) {
                    console.error('时间格式错误:', formattedEndTime);
                    wx.showToast({
                        title: '时间格式错误',
                        icon: 'none'
                    });
                    return;
                }

                const now = Date.now();
                const remainingTime = Math.max(endTime - now, 0);

                // 更新数据
                this.setData({
                    flashSaleInfo: {
                        ...this.data.flashSaleInfo,
                        ...product, // 合并 product 信息
                        flashPrice: flashPrice,
                        stock: stock,
                        activityType: activityType,
                        activityName: activityType.activityName || '',
                        endTime: endTimeStr,
                        formattedEndTime: formattedEndTime
                    },
                    time: remainingTime,
                    timeData: this.getTimeData(remainingTime)
                }, () => {
                    console.log('更新后的活动结束时间:', this.data.flashSaleInfo.endTime);
                });
            } else {
                console.error('获取活动信息失败', res);
                wx.showToast({
                    title: '获取活动信息失败',
                    icon: 'none'
                });
            }
        }, (err) => {
            console.error('活动信息请求失败:', err);
            wx.showToast({
                title: '活动信息加载失败',
                icon: 'none'
            });
        });
    },

    // 时间格式化
    getTimeData(ms) {
        let totalSeconds = Math.floor(ms / 1000);
        const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
        totalSeconds %= 3600;
        const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
        const seconds = String(totalSeconds % 60).padStart(2, '0');
        return {
            hours,
            minutes,
            seconds
        };
    },

    /**
     * 获取评论
     */
    getComments(productId) {
        http.GET('/comment/comments/list', {
            productId
        }, (res) => {
            if (res.code === 200 && res.rows) {
                // 1. 过滤掉orderId为null/undefined/空值的评论
                const validComments = res.rows.filter(comment => {
                    // 打印每条评论的orderId用于调试
                    console.log('评论orderId:', comment.orderId, '类型:', typeof comment.orderId);
                    // 过滤条件：排除null、undefined和空字符串
                    return comment.orderId !== null &&
                        comment.orderId !== undefined &&
                        comment.orderId !== '';
                });

               

                // 2. 从有效评论中取前3条
                const limitedRows = validComments.slice(0, 3);

                const comments = limitedRows.map(comment => {
                    let imgUrls = [];
                    if (comment.imageUrls) {
                        imgUrls = comment.imageUrls.split(',').map(url => url.trim());
                    } else if (comment.imageUrlList && comment.imageUrlList.length > 0) {
                        imgUrls = comment.imageUrlList;
                    }
                    return {
                        avatarUrl: comment.avatar || 'https://xxx/default.png',
                        name: comment.userName || '匿名用户',
                        time: comment.createdAt || '',
                        score: comment.rating || 5,
                        text: comment.content || '',
                        imgUrls
                    };
                });

                // 3. 使用过滤后的评论数据和数量
                this.setData({
                    appraise: comments,
                    appraiseNum: validComments.length // 显示有效评论总数
                });
            } else {
                wx.showToast({
                    title: '获取评论失败',
                    icon: 'none'
                });
            }
        }, (err) => {
            wx.showToast({
                title: '评论加载失败',
                icon: 'none'
            });
            console.error('获取评论失败:', err);
        });
    },

    onChange(e) {
        this.setData({
            timeData: e.detail
        });
    },

    toviews() {
        const productId = this.data.flashSaleInfo.id;
        wx.navigateTo({
            url: `/index/pages/mzhGoodsReviews/mzhGoodsReviews?productId=${productId}`,
        });
    },

    onPullDownRefresh() {
        if (this.productId) {
            this.getFlashSaleDetail(this.productId, () => {
                this.getActivityInfo(this.productId);
            });
            this.getComments(this.productId);
        }
        wx.stopPullDownRefresh();
    },

    onClickIcon() {
        wx.switchTab({
            url: '/pages/shopCart/shopCart',
        })
    },

    onClickButton() {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo || !userInfo.userId) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        const {
            flashSaleInfo
        } = this.data;
        const productId = flashSaleInfo.id;

        if (!productId) {
            wx.showToast({
                title: '商品信息有误',
                icon: 'none'
            });
            return;
        }

        const price = flashSaleInfo.flashPrice || flashSaleInfo.price;
        if (!price) {
            wx.showToast({
                title: '商品价格信息有误',
                icon: 'none'
            });
            return;
        }

        const cutoffTime = flashSaleInfo.activityType?.endTime;
        if (!cutoffTime) {
            wx.showToast({
                title: '活动时间信息有误',
                icon: 'none'
            });
            return;
        }

        const params = {
            userId: userInfo.userId,
            productId: productId,
            quantity: 1,
            price: price,
            cutoffTime: cutoffTime
        };

        console.log('提交的参数:', params);

        wx.showLoading({
            title: '加入购物车中...'
        });

        http.POST('/order/items', params, (res) => {
            wx.hideLoading();
            if (res.code === 200) {
                wx.showToast({
                    title: '加入购物车成功',
                    icon: 'success'
                });
                  // 👇 加入购物车成功后，更新 cartCount
                  this.setData({
                      cartCount: this.data.cartCount + 1
                  });
            } else {
                wx.showToast({
                    title: res.msg || '加入购物车失败',
                    icon: 'none'
                });
            }
        }, (err) => {
            wx.hideLoading();
            wx.showToast({
                title: '网络错误，加入失败',
                icon: 'none'
            });
            console.error('加入购物车失败:', err);
        });
    },
      onShow() {
          const userInfo = wx.getStorageSync('userInfo');
          if (userInfo && userInfo.userId) {
              http.GET(`/order/items/user/${userInfo.userId}`, {}, (res) => {
                  if (res.code === 200) {
                      let total = 0;
                      res.data.forEach(item => {
                          total += item.quantity;
                      });
                      this.setData({
                          cartCount: total
                      });
                  }
              });
          }
      },
});
